import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { convertToTreeData, getRolePermissions } from '@/utils/permissions'
import { PERMISSIONS } from "@/config/permissionConfig"
import { baseRoutes } from '@/router/routes'
import { filterRoutes } from '@/router/routeFilter'
import { getPermissionApi } from '@/api/auth'
import { useUserStore } from './userinfo'
import { useRouter } from 'vue-router'
export const usePermissionStore = defineStore('permission', () => {
    let router = useRouter()
    const userPermissions = ref([])
    const filteredRoutes = ref([])
    const permissionTreeData = computed(() => {
        return convertToTreeData(PERMISSIONS, getRolePermissions('companyAdmin').filter(permission => userPermissions.value.includes(permission)))
    })

    const hasPermission = computed(() => {
        return (permissionCode) => userPermissions.value.includes(permissionCode)
    })

    async function updateUserPermissions() {
        try {
            let localPermissions = JSON.parse(localStorage.getItem('permissions'))
            if (localPermissions) {
                userPermissions.value = localPermissions
            } else {
                let userStore = useUserStore()
                if (!userStore.userinfo || !userStore.userinfo.id) {
                    localStorage.removeItem('permissions')
                    localStorage.removeItem('token')
                    return router.push('/login')
                }
                let res = await getPermissionApi({
                    id: userStore.userinfo.id
                })

                let permissions = res.data
                localStorage.setItem('permissions', JSON.stringify(permissions))
                userPermissions.value = permissions
            }

            filterRoutesByPermissions()
        } catch (error) {
            console.error('Error fetching user permissions:', error)
        }
    }

    function filterRoutesByPermissions() {
        let routes = filterRoutes(baseRoutes, userPermissions.value)
        // 去重路由
        routes = Array.from(new Set(routes))
        filteredRoutes.value = routes
        routes = routes.filter(route => route.path !== '/login' && route.path !== '/test')

        for (let i = 0; i < routes.length; i++) {
            router.addRoute(routes[i])
        }

        router.options.routes = router.options.routes.concat(routes)
    }

    return {
        userPermissions,
        permissionTreeData,
        hasPermission,
        filteredRoutes,
        updateUserPermissions,
    }
})